import React, { useEffect, useState, useRef } from 'react';
import { jsapi, layerCreator, viewUtils, layerUtils } from '@/utils/arcgis';

function defaultCallback(lyr) {}

export const REAL_LYR_TYPE = {
  WebTileLayer: 'WebTileLayer',
  GraphicsLayer: 'GraphicsLayer',
  TileLayer: 'TileLayer',
  IntegratedMeshLayer: 'mesh',
  PointCloudLayer: 'pointcloud',
  SceneLayer: 'SceneLayer',
  BuildingSceneLayer: 'building',
  FeatureLayer: 'feature',
  MapImageLayer: 'Map Service',
  ImageryLayer: 'Image Service',
  ElevationLayer: 'dem',
  TileLayer: 'tile',
  VectorTileLayer: 'VectorTileLayer',
  // 'MapImageLayer':'dynamic',
};

const falsyArr = ['null', '{}', 'undefined', ''];

function useLayer(cfg) {
  const lyrRef = useRef(null);
  const cfgRef = useRef(cfg);
  const cfgStr = JSON.stringify(cfg);

  useEffect(() => {
    cfgRef.current = cfg;
  }, [cfg]);

  // 当图层为url时自动创建图层
  useEffect(() => {
    if (falsyArr.indexOf(cfgStr) !== -1) {
      return;
    }
    reLaunchLayer(cfgRef.current);
    return () => {};
  }, [cfgStr]);

  async function createLayer(cfg) {
    console.log('uselayer------createLayer');
    lyrRef.current = await layerCreator.create(cfg);
    const view = await viewUtils.isViewReady();
    view.map.add(lyrRef.current);
    return lyrRef.current;
  }

  function hideLayer(callback = defaultCallback) {
    if (!lyrRef.current) {
      console.error('图层未初始化');
      return;
    }
    lyrRef.current.visible = false;
    window.agsGlobal.view.popup.close();
    callback && callback(lyrRef.current);
    // todo 高亮 和 popup
  }

  function showLayer(callback = defaultCallback) {
    if (!lyrRef.current) {
      console.error('图层未初始化');
      return;
    }
    lyrRef.current.visible = true;
    callback && callback(lyrRef.current);
  }

  function setLayer(targetValue, cb) {
    if (!lyrRef.current) {
      console.error('图层未初始化');
      return;
    }
    lyrRef.current.set(targetValue || {});
    cb && cb(lyrRef.current);
  }

  // 方便用于异步自定义数据的图层
  async function reLaunchLayer(config) {
    console.log('uselayer------reLaunchLayer');
    if (!config) {
      console.warn('配置为空');
    }
    if (lyrRef.current) {
      const view = await viewUtils.isViewReady();
      view.map.remove(lyrRef.current);
    }
    const lyr = await createLayer(config);
    return lyr;
  }

  return [
    lyrRef.current,
    {
      hideLayer,
      showLayer,
      setLayer,
      reLaunchLayer,
      createLayer,
    },
  ];
}

export default useLayer;
